package com.car.action.admin;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;

import com.alibaba.fastjson.JSONObject;
import com.car.common.model.AdminUser;
import com.car.common.model.Area;
import com.car.common.model.Card;
import com.car.common.model.CardDiscuss;
import com.car.common.model.Message;
import com.car.common.model.NavyUsers;
import com.car.common.model.UserHellos;
import com.car.common.model.Users;
import com.car.common.model.UsersInfo;
import com.car.common.model.VipRecord;
import com.car.intercept.AdminInterceptor;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.core.ForwardActionRender;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.render.Render;
import com.qiniu.util.StringUtils;
import com.utils.CookiesUtil;
import com.utils.DateUtil;
import com.utils.HttpRequestUtil;
import com.utils.PicUtil;
import com.utils.RongCloudUtil;
import com.utils.StringUtil;
import com.utils.SystemClock;
import com.utils.Toolkit;
import com.vdurmont.emoji.EmojiParser;


public class LoginController  extends Controller {
	public final static String ADMIN_SESSION_KEY = "admin_user";
	
	public void index() {
		if (getSessionAttr(ADMIN_SESSION_KEY) != null) {
			
		}
		render("index.html");
	}
	
	public void login() {
		if (getSessionAttr(ADMIN_SESSION_KEY) == null) {
			AdminUser user = new AdminUser().login(getPara("user_name"), getPara("user_password"));
			if (user == null) {
				setAttr("message", "账号或密码错误");
				render("index.html");
			} else {
				setSessionAttr(ADMIN_SESSION_KEY, user);
				main();
			}
		} else {
			main();
		}
	}

	@Before(AdminInterceptor.class)
	public void main() {
		Users all = Users.dao.findFirst("select count(id) as cnt from users ");
		setAttr("all", all.get("cnt"));
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		Users yestoday = Users.dao.findFirst("select count(id) as cnt from users where is_true = 1 and  FROM_UNIXTIME(create_time, '%Y-%m-%d') = '" + DateUtil.commonDateFormat.format(calendar.getTime()) +"'");
		setAttr("yestoday", yestoday.get("cnt"));
		
		
		Card yestoday_card_2 = Card.dao.findFirst("select count(c.id) as cnt from card as c  LEFT JOIN users as u on u.id = c.user_id  where u.sex = 2 and u.is_true > 1 and FROM_UNIXTIME(c.create_time, '%Y-%m-%d') = '" + DateUtil.commonDateFormat.format(calendar.getTime()) +"'");
		setAttr("yestoday_card_2", yestoday_card_2.get("cnt"));
		
		
		CardDiscuss yestoday_discuss_1 = CardDiscuss.dao.findFirst("select count(d.id) as cnt from card_discuss as d  LEFT JOIN users as u on u.id = d.user_id  where u.is_true = 1 and FROM_UNIXTIME(d.create_time, '%Y-%m-%d') = '" + DateUtil.commonDateFormat.format(calendar.getTime()) +"'");
		setAttr("yestoday_discuss_1", yestoday_discuss_1.get("cnt"));
		
		
		CardDiscuss yestoday_discuss_2 = CardDiscuss.dao.findFirst("select count(d.id) as cnt from card_discuss as d  LEFT JOIN users as u on u.id = d.user_id  where u.is_true > 1 and FROM_UNIXTIME(d.create_time, '%Y-%m-%d') = '" + DateUtil.commonDateFormat.format(calendar.getTime()) +"'");
		setAttr("yestoday_discuss_2", yestoday_discuss_2.get("cnt"));
		
		//user_hellos
		UserHellos yestoday_friends = UserHellos.dao.findFirst("select count(id) as cnt from user_hellos where FROM_UNIXTIME(create_time, '%Y-%m-%d') = '" + DateUtil.commonDateFormat.format(calendar.getTime()) +"'");
		setAttr("yestoday_friends", yestoday_friends.get("cnt"));
		
		
		Map<String,Object> echarts = CacheKit.get("constant", "echarts");
		if (echarts == null) {
			List<String> keyList = Lists.newArrayList();
			List userValueList = Lists.newArrayList();
			List androidValueList = Lists.newArrayList();
			List iosValueList = Lists.newArrayList();
			calendar.add(Calendar.DAY_OF_MONTH, -12);
			for(int i =-14; i<=-2;i++) {
				calendar.add(Calendar.DAY_OF_MONTH, 1);
				String time = DateUtil.commonDateFormat.format(calendar.getTime());
				
				Users oneday = Users.dao.findFirst("select count(id) as cnt from users where is_true = 1 and FROM_UNIXTIME(create_time, '%Y-%m-%d') = '" + time +"'");
				keyList.add("\"" + time + "\"");
				userValueList.add(oneday.get("cnt"));
				VipRecord android = VipRecord.dao.findFirst("select SUM(price) as price from  vip_record where (buy_type = 'WxPay' or buy_type = 'AliPay') and `status` = 1 and  FROM_UNIXTIME(create_time, '%Y-%m-%d') = '" + time +"'"); 
				// create_time > 1555171200
				androidValueList.add(android.get("price") == null ? 0 :android.get("price"));
				
				VipRecord ios = VipRecord.dao.findFirst("select SUM(0.7 * price) as price from  vip_record where buy_type = 'ApplePay' and `status` = 1 and  FROM_UNIXTIME(create_time, '%Y-%m-%d') = '" + time +"'");
				iosValueList.add(ios.get("price") == null ? 0 :ios.get("price"));
			}
			echarts = Maps.newHashMap();
			setAttr("key", StringUtils.join(keyList, ","));
			echarts.put("key", StringUtils.join(keyList, ","));
			setAttr("users", StringUtils.join(userValueList, ","));
			echarts.put("users", StringUtils.join(userValueList, ","));
			setAttr("android", StringUtils.join(androidValueList, ","));
			echarts.put("android", StringUtils.join(androidValueList, ","));
			setAttr("ios", StringUtils.join(iosValueList, ","));
			echarts.put("ios", StringUtils.join(iosValueList, ","));
			CacheKit.put("constant", "echarts", echarts);
		} else {
			setAttrs(echarts);
//			setAttr("key", echarts.get("key"));
//			setAttr("users", echarts.get("users"));
//			setAttr("android", echarts.get("android"));
//			setAttr("ios", echarts.get("ios"));
		}
		render("main.html");
	}
	
	@Before(AdminInterceptor.class)
	public void area() {
		String time = getPara("time");
		if (StringUtil.empty(time)) {
			time = DateUtil.echartsTimeFormat.format(new Date());
		}
		Map<String,Object> echarts = CacheKit.get("constant", "area_echarts_" + time);
		if (echarts == null) {
			echarts = Maps.newHashMap();
			List<String> keyList = Lists.newArrayList();
			List<String> usersList = Lists.newArrayList();
			List<String> vipList = Lists.newArrayList();
			List<String> cardList = Lists.newArrayList();
			/*
			List<Area> areaList = Area.dao.find("select code,name from area where parent_id = 1 ");
			for(Area one :areaList) {
				keyList.add( "\"" + one.getName() + "\"");
				Users areausers = Users.dao.findFirst("select count(id) as cnt from users where area_id = " + one.getCode() +" and FROM_UNIXTIME(create_time, '%Y-%m') = '" + time +"'" );
				usersList.add(String.valueOf(areausers.getLong("cnt")));
				VipRecord vipusers = VipRecord.dao.findFirst("select SUM(vip.price) as price from  vip_record as vip left join users as u on vip.user_id = u.id where (buy_type = 'WxPay' or buy_type = 'AliPay' or buy_type = 'ApplePay') and vip.`status` = 1 and  area_id = " + one.getCode() +" and FROM_UNIXTIME(vip.create_time, '%Y-%m') = '" + time +"'"  );
				vipList.add(vipusers == null ? "0" :  (vipusers.getPrice() == null) ? "0" : vipusers.getBigDecimal("price").toString());
				
				Card cardusers = Card.dao.findFirst("select count(card.id) as cnt from card left join users as u on card.user_id = u.id where u.area_id = " + one.getCode() +" and FROM_UNIXTIME(card.create_time, '%Y-%m') = '" + time +"'"  );
				cardList.add(String.valueOf(cardusers.getLong("cnt")));
			}
			*/
			List<String> persons = Lists.newArrayList();
			persons.add("1");
			persons.add("2");
			persons.add("3");
			persons.add("4");
			for(String person :persons) {
				String name = "";
				if ("1".equals(person)) {
					name = "袁杰";
				} else if ("2".equals(person)) {
					name = "李扬";
				} else if ("3".equals(person)) {
					name = "张炜";
				} else if ("4".equals(person)) {
					name = "常少彪";
				}
				keyList.add( "\"" + name + "\"");
				Users areausers = Users.dao.findFirst("select count(id) as cnt from users where FROM_UNIXTIME(create_time, '%Y-%m') = '" + time +"' " + StringUtil.getSQLForPerson(person) );
				usersList.add(String.valueOf(areausers.getLong("cnt")));
				VipRecord vipusers_Android = VipRecord.dao.findFirst("select SUM(vip.price) as price from  vip_record as vip left join users as u on vip.user_id = u.id where (buy_type = 'WxPay' or buy_type = 'AliPay') and vip.`status` = 1 and  FROM_UNIXTIME(vip.create_time, '%Y-%m') = '" + time +"'" + StringUtil.getSQLForPerson(person)  );
				
				VipRecord vipusers_Ios = VipRecord.dao.findFirst("select SUM(0.7 * vip.price) as price from  vip_record as vip left join users as u on vip.user_id = u.id where buy_type = 'ApplePay' and vip.`status` = 1 and  FROM_UNIXTIME(vip.create_time, '%Y-%m') = '" + time +"'" + StringUtil.getSQLForPerson(person)  );
				vipList.add(vipusers_Android.getPrice().add(vipusers_Ios.getPrice()).toString());
				
				Card cardusers = Card.dao.findFirst("select count(card.id) as cnt from card left join users as u on card.user_id = u.id where FROM_UNIXTIME(card.create_time, '%Y-%m') = '" + time +"'" + StringUtil.getSQLForPerson(person)  );
				cardList.add(String.valueOf(cardusers.getLong("cnt")));
			}
			
			setAttr("key", StringUtils.join(keyList, ","));
			echarts.put("key", StringUtils.join(keyList, ","));
			
			setAttr("usersList", StringUtils.join(usersList, ","));
			echarts.put("usersList", StringUtils.join(usersList, ","));
			
			setAttr("vipList", StringUtils.join(vipList, ","));
			echarts.put("vipList", StringUtils.join(vipList, ","));
			
			setAttr("cardList", StringUtils.join(cardList, ","));
			echarts.put("cardList", StringUtils.join(cardList, ","));
			CacheKit.put("constant", "area_echarts", echarts);
		} else {
			setAttrs(echarts);
		}
		setAttr("time", time);
		render("area.html");
	}
	
	public void message() {
		Message one = new Message();
		one.set("fromUserId", getPara("fromUserId"));
		one.set("toUserId", getPara("toUserId"));
		String toUserId = getPara("toUserId");
		Users toUsers = Users.dao.findById(toUserId);
		if (toUsers == null ) {
			renderText("200");
			return ;
		} else if (toUsers.getIsTrue() == 1 || toUsers.getIsTrue() == 4) { 
			one.set("admin", 0);
		} else {
			one.set("admin", 1);
//			one.set("area_id", toUsers.getAreaId());
		}
		/*
		NavyUsers navyUsers = NavyUsers.dao.findFirst("select id from navy_users where user_id = '" +toUserId +"' order by id desc limit 1 ");
		if (navyUsers == null) {
			one.set("admin", 0);	
		} else {
			one.set("admin", 1);
		}
		*/
		one.set("objectName", getPara("objectName"));
		String content = EmojiParser.parseToAliases(getPara("content")); 
		one.set("content", content);
		one.set("channelType", getPara("channelType"));
		one.set("msgTimestamp", getPara("msgTimestamp"));
		one.set("msgUID", getPara("msgUID"));
		one.set("sensitiveType", getPara("sensitiveType"));
		one.set("source", getPara("source"));
		one.set("groupUserIds", getPara("groupUserIds"));
		try {
			one.save();
		}catch (Exception e) {
			e.printStackTrace();
		}
		renderText("200");
	}
	
	public void test_loc() {
		List<Users> usersList = Users.dao.find("select id from users where  is_true > 1 order by id desc ");
		for(Users users:usersList) {
			long user_id = users.getId();
			UsersInfo users_info = UsersInfo.dao.findFirst("select * from users_info where user_id = " + user_id);
			if (users_info != null) {
				String lat = users_info.getLat();
				String lng = users_info.getLng();
				if (StringUtil.empty(lat) || StringUtil.empty(lng)) {
					String gps =  Toolkit.getRandGPS(new Double(114.170434), new Double(30.552575), 6500000.0);
					String new_lat = gps.split(",")[0];
					String new_lng = gps.split(",")[1];
					// 没位置设置A点
					System.out.println("update users_info set lat = " + new_lat +",lng =" + new_lng +" where user_id= " + user_id +";");
//					Db.update("update users_info set lat = " + new_lat +",lng =" + new_lng +" where user_id= " + user_id);
					// 水军设置B点
					String gps2 =  Toolkit.getRandGPS(new Double(new_lat), new Double(new_lng), 2000000.0);
					String lat_A = gps2.split(",")[0];
					String lng_A = gps2.split(",")[1];
					System.out.println("update users_info set lat_A = " + lat_A +",lng_A =" + lng_A +" where user_id= " + user_id+";");
//					Db.update("update users_info set lat_A = " + lat_A +",lng_A =" + lng_A +" where user_id= " + user_id);
				}
			}
		}
		renderText("操作成功!");
	}
	
	public void test () {
		List<Users> usersList = Users.dao.find("select id,user_header from users where  sex=1 and is_true > 1 and user_header is not null and id > 100000 order by id desc ");
		for(Users users:usersList) {
			if (users != null && !StringUtil.empty(users.getUserHeader())  ) {
			HttpClient client = new HttpClient();
	    	client.getParams().setContentCharset("UTF-8");
	    	String url = PicUtil.QINIU_DIR + users.getUserHeader();
	    	if (url.indexOf(" ") == -1 ) {
	    		PostMethod postMethod = new PostMethod(url);
				try {
//					String path = "D:\\head";		//要遍历的路径
//					File file = new File(path);		//获取其file对象
//					File[] fs = file.listFiles();	//遍历path下的文件和目录，放在File数组中
//					for(File f:fs){					//遍历File[]数组
//						if(!f.isDirectory())	{
//							new PicUtil().upload(path+"\\"+f.getName(), "auth_user_head_0916"+f.getName());
//							System.out.println("update users set user_header='auth_user_head_0916"+f.getName()+"' where id=" +users.getId()+";");
//							//String newurl= "http://api.50duhui.top/user_info/update?user_header=auth_user_head_"+f.getName()+"&token="+JwtToken.createToken(users.getId());
//							//System.out.println("newurl="+newurl);
//							//System.out.println(HttpRequestUtil.sendGet(newurl));
//							//System.out.println("f.delete()="+);
//							f.delete();
//							f.deleteOnExit();
//							break;
//						}
//					}
					int status = client.executeMethod(postMethod);
					if (status == HttpStatus.SC_OK) {
						
					} else {
						//Db.update("update users set user_header = null,is_true = 1  where id = " + users.getId());
						String path = "D:\\head2";		//要遍历的路径
						File file = new File(path);		//获取其file对象
						File[] fs = file.listFiles();	//遍历path下的文件和目录，放在File数组中
						for(File f:fs){					//遍历File[]数组
							if(!f.isDirectory())	{
								new PicUtil().upload(path+"\\"+f.getName(), "auth_user_head_0916"+f.getName());
								System.out.println("update users set user_header='auth_user_head_0916"+f.getName()+"' where id=" +users.getId()+";");
								//String newurl= "http://api.50duhui.top/user_info/update?user_header=auth_user_head_"+f.getName()+"&token="+JwtToken.createToken(users.getId());
								//System.out.println("newurl="+newurl);
								//System.out.println(HttpRequestUtil.sendGet(newurl));
								//System.out.println("f.delete()="+);
								f.delete();
								f.deleteOnExit();
								break;
							}
						}
						
					}
				} catch (HttpException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	    	}
	    	
		}
		}
		renderText("OK");
	}
	
	public void auto_create() {
		long user_mobile = 18000003140L;
		for (int i = 0 ;i < 50; i ++) {
			user_mobile++;
			Users users = Users.dao.findFirst("select id from users where user_mobile ='"+ user_mobile+"'");
			if (users == null) {
				users = new Users();
				users.setUserMobile(String.valueOf(user_mobile));
				users.setUserPassword(Users.password("花花爱我"));
				users.setSex(2);
				// 模板1
				int tempid = 1 + new Random().nextInt(10);
				if (tempid ==1) {
					users.setTagIds("16,43,45,67,68,62,47,29,39,66");
					users.setBirthday(835408408L);
				} else if (tempid == 2) {
					users.setTagIds("16,45,67,68,62,29,38,26,10,56");
					users.setBirthday(935286808L);
				} else if (tempid == 3) {
					users.setTagIds("16,43,67,68,62,39,49,66");
					users.setBirthday(933818008L);
				} else if (tempid == 4) {
					users.setTagIds("16,43,67,62,29,39,50");
					users.setBirthday(812858008L);
				} else if (tempid == 5) {
					users.setTagIds("16,43,45,67,68,62,47,35,39");
					users.setBirthday(853466008L);
				} else if (tempid == 6) {
					users.setTagIds("16,43,,67,68,47,39,26");
					users.setBirthday(880250008L);
				} else if (tempid == 7) {
					users.setTagIds("16,43,45,67,39,49,38,66");
					users.setBirthday(821670808L);
				} else if (tempid == 8) {
					users.setTagIds("16,45,67,68,47,39,56");
					users.setBirthday(905478808L);
				} else if (tempid == 9) {
					users.setTagIds("16,43,45,67,68");
					users.setBirthday(935459608L);
				} else if (tempid == 10) {
					users.setTagIds("16,43,45,35,39,50");
					users.setBirthday(875584408L);
				}
				users.setCreateTime(SystemClock.now()/1000L);
				users.setUpdateTime(SystemClock.now()/1000L);
				users.setIsTrue(2);
				users.save();
				
				Long user_id = users.getId();
				
				NavyUsers nusers = new NavyUsers();
				nusers.setUserId(user_id.intValue());
				nusers.setAdminUserId(46);
				nusers.save();
				UsersInfo info = new UsersInfo();
				info.setUserId(user_id.intValue());
				if (tempid ==1) {
					info.setHeight(166);
					info.setWeight(47);
					// 情感状态
					info.setOrientation(1);
					info.setEmotion(2);
				} else if (tempid == 2) {
					info.setHeight(164);
					info.setWeight(45);
					// 情感状态
					info.setOrientation(1);
					info.setEmotion(2);
				} else if (tempid == 3) {
					info.setHeight(171);
					info.setWeight(50);
					// 情感状态
					info.setOrientation(1);
					info.setEmotion(2);
				} else if (tempid == 4) {
					info.setHeight(168);
					info.setWeight(49);
					// 情感状态
					info.setOrientation(1);
					info.setEmotion(2);
				} else if (tempid == 5) {
					info.setHeight(163);
					info.setWeight(43);
					// 情感状态
					info.setOrientation(1);
					info.setEmotion(2);
				} else if (tempid == 6) {
					info.setHeight(165);
					info.setWeight(45);
					// 情感状态
					info.setOrientation(1);
					info.setEmotion(2);
				} else if (tempid == 7) {
					info.setHeight(156);
					info.setWeight(47);
					// 情感状态
					info.setOrientation(1);
					info.setEmotion(2);
				} else if (tempid == 8) {
					info.setHeight(153);
					info.setWeight(43);
					// 情感状态
					info.setOrientation(1);
					info.setEmotion(2);
				} else if (tempid == 9) {
					info.setHeight(171);
					info.setWeight(53);
					// 情感状态
					info.setOrientation(3);
					info.setEmotion(2);
				} else if (tempid == 10) {
					info.setHeight(166);
					info.setWeight(48);
					// 情感状态
					info.setOrientation(3);
					info.setEmotion(2);
				} 
				info.save();
			}
			
		}
		renderText("OK");
	}
	
	
	public void create() {
		try {
			FileReader fr = new FileReader("D:\\nickname.txt"); 
			BufferedReader buf = new BufferedReader(fr);
			String s; 
			int i = 1;
			while((s = buf.readLine() ) != null){
				//System.out.println(s);
				i++;
				try {
					String nickname = s;
					Users users = new Users();
					users.setNickName(StringUtil.encode(nickname));
					users.setUserPassword(Users.password("花花爱我"));
					users.setSex(2);
					// 模板1
					int tempid = 1 + new Random().nextInt(10);
					if (tempid ==1) {
						users.setTagIds("16,43,45,67,68,62,47,29,39,66");
						users.setBirthday(835408408L);
					} else if (tempid == 2) {
						users.setTagIds("16,45,67,68,62,29,38,26,10,56");
						users.setBirthday(935286808L);
					} else if (tempid == 3) {
						users.setTagIds("16,43,67,68,62,39,49,66");
						users.setBirthday(933818008L);
					} else if (tempid == 4) {
						users.setTagIds("16,43,67,62,29,39,50");
						users.setBirthday(812858008L);
					} else if (tempid == 5) {
						users.setTagIds("16,43,45,67,68,62,47,35,39");
						users.setBirthday(853466008L);
					} else if (tempid == 6) {
						users.setTagIds("16,43,,67,68,47,39,26");
						users.setBirthday(880250008L);
					} else if (tempid == 7) {
						users.setTagIds("16,43,45,67,39,49,38,66");
						users.setBirthday(821670808L);
					} else if (tempid == 8) {
						users.setTagIds("16,45,67,68,47,39,56");
						users.setBirthday(905478808L);
					} else if (tempid == 9) {
						users.setTagIds("16,43,45,67,68");
						users.setBirthday(935459608L);
					} else if (tempid == 10) {
						users.setTagIds("16,43,45,35,39,50");
						users.setBirthday(875584408L);
					}
					users.setCreateTime(SystemClock.now()/1000L);
					users.setUpdateTime(SystemClock.now()/1000L);
					users.setIsTrue(2);
					String path = "D:\\head2";		//要遍历的路径
					File file = new File(path);		//获取其file对象
					File[] fs = file.listFiles();	//遍历path下的文件和目录，放在File数组中
					for(File f:fs){					//遍历File[]数组
						if(!f.isDirectory())	{
							new PicUtil().upload(path+"\\" + f.getName(), "auth_user_head_1029"+f.getName());
							users.setUserHeader("auth_user_head_1029"+ f.getName());
//							System.out.println("update users set user_header='auth_user_head_1029"+f.getName()+"' where id=" +users.getId()+";");
							//String newurl= "http://api.50duhui.top/user_info/update?user_header=auth_user_head_"+f.getName()+"&token="+JwtToken.createToken(users.getId());
							//System.out.println("newurl="+newurl);
							//System.out.println(HttpRequestUtil.sendGet(newurl));
							//System.out.println("f.delete()="+);
							f.delete();
							f.deleteOnExit();
							break;
						}
					}
					users.save();
					Long user_id = users.getId();
					UsersInfo info = new UsersInfo();
					info.setUserId(user_id.intValue());
					if (tempid ==1) {
						info.setHeight(166);
						info.setWeight(47);
						// 情感状态
						info.setOrientation(1);
						info.setEmotion(2);
					} else if (tempid == 2) {
						info.setHeight(164);
						info.setWeight(45);
						// 情感状态
						info.setOrientation(1);
						info.setEmotion(2);
					} else if (tempid == 3) {
						info.setHeight(171);
						info.setWeight(50);
						// 情感状态
						info.setOrientation(1);
						info.setEmotion(2);
					} else if (tempid == 4) {
						info.setHeight(168);
						info.setWeight(49);
						// 情感状态
						info.setOrientation(1);
						info.setEmotion(2);
					} else if (tempid == 5) {
						info.setHeight(163);
						info.setWeight(43);
						// 情感状态
						info.setOrientation(1);
						info.setEmotion(2);
					} else if (tempid == 6) {
						info.setHeight(165);
						info.setWeight(45);
						// 情感状态
						info.setOrientation(1);
						info.setEmotion(2);
					} else if (tempid == 7) {
						info.setHeight(156);
						info.setWeight(47);
						// 情感状态
						info.setOrientation(1);
						info.setEmotion(2);
					} else if (tempid == 8) {
						info.setHeight(153);
						info.setWeight(43);
						// 情感状态
						info.setOrientation(1);
						info.setEmotion(2);
					} else if (tempid == 9) {
						info.setHeight(171);
						info.setWeight(53);
						// 情感状态
						info.setOrientation(3);
						info.setEmotion(2);
					} else if (tempid == 10) {
						info.setHeight(166);
						info.setWeight(48);
						// 情感状态
						info.setOrientation(3);
						info.setEmotion(2);
					} 
					info.save();
				} catch (Exception e) {
					
				}
			}
			fr.close(); 
			buf.close();
		}catch(IOException e){
			e.printStackTrace();
		} 
		renderJson("OK啦");
	}

	
	public void exit() {
		setSessionAttr(ADMIN_SESSION_KEY, null);
		index();
	}
	
	public void clear_person() {
		CookiesUtil.remove(getRequest(), getResponse(), "person");
		renderJson("处理完成");
	}
	
	

	/*
	 * 随机生成国内IP地址
	 */
	public static String getRandomIp() {
 
		// ip范围
		int[][] range = { { 607649792, 608174079 },// 36.56.0.0-36.63.255.255
				{ 1038614528, 1039007743 },// 61.232.0.0-61.237.255.255
				{ 1783627776, 1784676351 },// 106.80.0.0-106.95.255.255
				{ 2035023872, 2035154943 },// 121.76.0.0-121.77.255.255
				{ 2078801920, 2079064063 },// 123.232.0.0-123.235.255.255
				{ -1950089216, -1948778497 },// 139.196.0.0-139.215.255.255
				{ -1425539072, -1425014785 },// 171.8.0.0-171.15.255.255
				{ -1236271104, -1235419137 },// 182.80.0.0-182.92.255.255
				{ -770113536, -768606209 },// 210.25.0.0-210.47.255.255
				{ -569376768, -564133889 }, // 222.16.0.0-222.95.255.255
		};
 
		Random rdint = new Random();
		int index = rdint.nextInt(10);
		String ip = num2ip(range[index][0] + new Random().nextInt(range[index][1] - range[index][0]));
		return ip;
	}
	
	/*
	 * 将十进制转换成ip地址
	 */
	public static String num2ip(int ip) {
		int[] b = new int[4];
		String x = "";
 
		b[0] = (int) ((ip >> 24) & 0xff);
		b[1] = (int) ((ip >> 16) & 0xff);
		b[2] = (int) ((ip >> 8) & 0xff);
		b[3] = (int) (ip & 0xff);
		x = Integer.toString(b[0]) + "." + Integer.toString(b[1]) + "." + Integer.toString(b[2]) + "." + Integer.toString(b[3]);
 
		return x;
	}

	public void chat_im() {
		PropKit.use("config.properties");
    	String appKey 		=  PropKit.get("im.rongcloud.appKey");
    	String appSecret    =  PropKit.get("im.rongcloud.appSecret");
    	setAttr("appKey", 	 appKey);
    	setAttr("appSecret", appSecret);
    	
    	String user_id = getPara("user_id");
    	UsersInfo info = UsersInfo.dao.findFirst("select im_token from users_info where user_id = " + user_id);
    	if (info == null || StringUtil.empty(info.getImToken())) {
    		Db.update("update users set login_status = 0 where id = " + user_id); 
			Users users = Users.dao.findById(user_id);
			if (users != null ) {
				/**
				 * 
				 userId	String	用户 Id，支持大小写英文字母、数字、部分特殊符号 + = - _ 的组合方式，最大长度 64 字节。是用户在 App 中的唯一标识，必须保证在同一个 App 内不重复，重复的用户 Id 将被当作是同一用户。（必传）
				 name	String	用户名称，最大长度 128 字节。用来在 Push 推送时显示用户的名称。（必传）
				 portraitUri	String	用户头像 URI，最大长度 1024 字节。（必传）
				 */
				Map<String, String> params = Maps.newHashMap();
				params.put("userId",   		String.valueOf(user_id));
				params.put("name",     		StringUtil.empty(users.getNickName())?"火星人": users.getNickName());
				if (StringUtil.empty(users.getUserHeader())) {
					params.put("portraitUri",     PicUtil.DEFAULT_HEAD);
				} else {
					params.put("portraitUri",     PicUtil.QINIU_DIR +  users.getUserHeader());
				}
				JSONObject jsonObject = RongCloudUtil.post("http://api-cn.ronghub.com/user/getToken.json", params);
				if (jsonObject.getIntValue("code") == 200) {
					
					String token = jsonObject.getString("token");
					
					Db.update("update users_info set im_token = '" + token + "' where user_id = " + user_id);
					setAttr("token", token);
				}
			}
    	} else {
    		setAttr("token", info.getImToken());
    	}
    	render("chat.html");
	}
	
	
	
	public void change() {
		List<Users> users = Users.dao.find("select id,nick_name from users ");
		for(Users one:users) {
			try {
				String nick_name2 = new String(StringUtil.decode(one.getNickName()).getBytes("gbk"),"utf-8");
				Db.update("update users set nick_name='"+ StringUtil.encode(nick_name2) +"' where id = " + one.getId());
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		renderJson("OK了");
	}
	
	
	/**
	  *   小程序增加评论
	 * @param id
	 * @param content
	 * @param area  
	 */
	public void giveDiscuss(){
		getResponse().setHeader("Access-Control-Allow-Origin", "*");
		int type = getParaToInt("type");
		String content = getPara("content");
		String area = getPara("area");
		Card card = Card.dao.findById(getPara("id"));
		try {
			new CardController().discuss(card,content,type,getPara("buser_id"),area);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		renderText("操作成功!");
	}
	
	
	public static void main(String[] args) throws Exception {
		FileReader fr = new FileReader("D:\\discuss.txt"); 
		BufferedReader buf = new BufferedReader(fr);
		String s; 
		int i = 1;
		while((s = buf.readLine() ) != null){
			System.out.println(StringUtil.decode(s));
		}
		/*
		String path = "D:\\head2";		//要遍历的路径
		File file = new File(path);		//获取其file对象
		File[] fs = file.listFiles();	//遍历path下的文件和目录，放在File数组中
		for(File f:fs){					//遍历File[]数组
			if(!f.isDirectory())	{
				i++;
				if (i < 1001) {
					try {
						new PicUtil().upload(path+"\\" + f.getName(), "auth_user_head_1030"+f.getName());
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("auth_user_head_1030"+ f.getName());
					f.delete();
					f.deleteOnExit();
				}
			
			}
		}
		/*
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		List<String> keyList = Lists.newArrayList();
		for(int i =-14; i<=-1;i++) {
			calendar.add(Calendar.DAY_OF_MONTH, -1);
			String time = DateUtil.commonDateFormat.format(calendar.getTime());
			keyList.add(time);
		}
		String key = StringUtils.join(keyList, ",");
		System.out.println(key);
		*/
	}
}

